﻿using CarAppDomain.CarParts.Entities;
using CarAppDomain.CarParts.IRepository;
using CarAppDomain.CarType.Entities;
using CarAppDomain.Sys.Entities;
using CarAppDomain.Sys.IRepositories;
using CarAppDto.CarParts.CarPartsDtos;
using CarAppDto.CarType.VehicleSeriesDtos;
using D.UtilSqlsugarOrm;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace CarAppDomain.CarParts.Repository
{
    public class CarPartsEntityRepository : BaseRepository<CarPartsEntity>, ICarPartsEntityRepository
    {
        private readonly ISqlSugarClient sqlSugarClient;
        public CarPartsEntityRepository(ISqlSugarClient db) : base(db)
        {
            sqlSugarClient = db;
        }

        /// <summary>
        /// 通过车系Id，查询配件信息
        /// </summary>
        /// <param name="carTpye"></param>
        /// <returns></returns>
        public async Task<List<RepCarParts>> GetCarPartsListByVehicleSeries(int pageSize, int current, string vehicleSeries)
        {
            RefAsync<int> totalCount = 0;//REF和OUT不支持异步,想要真的异步这是最优解
            var list = await sqlSugarClient.Queryable<CarPartsEntity>()
              .LeftJoin<VehicleSeriesCarPartsTypeEntity>((cp, t) => cp.CarPartsTypeId == t.Id)
              .Where((cp,  t) => cp.VehicleSeriesId == vehicleSeries)
              .OrderBy((cp, t) => cp.CreateTime, OrderByType.Desc).Select<RepCarParts>().ToListAsync();
            return list;
            //return new PageModel<RepCarParts>() { Data = list, TotalCount = totalCount, TotalPage = (int)Math.Ceiling(totalCount / (double)pageSize) };

        }

        /// <summary>
        /// 通过车型版本Id，查询配件信息
        /// </summary>
        /// <param name="carTpye"></param>
        /// <returns></returns>
        public async Task<List<RepCarPartsCarTypeVersion>> GetCarPartsCarTypeVersion(string carTpyeVersion)
        {
            return await sqlSugarClient.Queryable<CarPartsEntity>().LeftJoin<CarPartsCarTypeVersionEntity>((cpe, cpctve) => cpe.Id == cpctve.CarPartsId)
                .LeftJoin<CarPartsTypeEntity>((cpe, cpctve, cpte) => cpe.CarPartsTypeId == cpte.Id)
           .Where((cpe, cpctve, cpte) => cpctve.CarTypeVersionId == carTpyeVersion).OrderBy((cpe, cpctve, cpte) => cpctve.SerialNumber).Select((cpe, cpctve, cpte) => new RepCarPartsCarTypeVersion
           {
               Id = cpe.Id,
               Name = cpe.Name,
               EnglishName = cpe.EnglishName,
               Code = cpe.Code,
               CarPartsTypeName = cpte.Name,
               ReplacedCarPartsId = cpctve.ReplacedCarPartsId,
               State = cpctve.State
           })
           .ToListAsync();
        }

        /// <summary>
        /// 获取所有列表
        /// </summary>
        /// <param name="where"></param>
        /// <param name="order"></param>
        /// <returns></returns>
        public async Task<List<RepCarParts>> GetListAsync(System.Linq.Expressions.Expression<Func<CarPartsEntity, bool>> where = null, System.Linq.Expressions.Expression<Func<CarPartsEntity, object>> order = null)
        {
            try
            {
                return await sqlSugarClient.Queryable<CarPartsEntity>().LeftJoin<CarPartsTypeEntity>((m, d) => m.CarPartsTypeId == d.Id).WhereIF(where != null, where).OrderByIF(order != null, order).Select<RepCarParts>().ToListAsync();

            }
            catch (Exception ex)
            {

                throw;
            }
        }


        //分页查询
        /// <summary>
        /// 分页查询 加入条件
        /// </summary>
        /// <param name="pageSize">每页显示多少条</param>
        /// <param name="current">当前第几页</param>
        /// <param name="where"></param>
        /// <param name="order"></param>
        /// <returns></returns>
        public async Task<PageModel<RepCarParts>> GetPagesAsync(int pageSize, int current, System.Linq.Expressions.Expression<Func<CarPartsEntity, bool>> where, System.Linq.Expressions.Expression<Func<CarPartsEntity, object>> order = null)
        {
            try
            {
                RefAsync<int> totalCount = 0;//REF和OUT不支持异步,想要真的异步这是最优解

                var list = await sqlSugarClient.Queryable<CarPartsEntity>().LeftJoin<CarPartsTypeEntity>((m, d) => m.CarPartsTypeId == d.Id).WhereIF(where != null, where).OrderByIF(order != null, order).Select<RepCarParts>().ToPageListAsync(current, pageSize, totalCount);
                return new PageModel<RepCarParts>() { Data = list, TotalCount = totalCount, TotalPage = (int)Math.Ceiling(totalCount / (double)pageSize) };


            }
            catch (Exception ex)
            {

                throw;
            }
    
        }

        /// <summary>
        /// 获取车型配件
        /// </summary>
        /// <param name="carTpye"></param>
        /// <returns></returns>
        public async Task<List<RepCarPartsCarTypeVersion>> GetCarPartsCarType(string carTpye)
        {
         var list = await sqlSugarClient.Queryable<CarPartsEntity>().LeftJoin<CarPartsCarTypeEntity>((cpe, cpctve) => cpe.Id == cpctve.CarPartsId)
              .LeftJoin<CarPartsTypeEntity>((cpe, cpctve, cpte) => cpe.CarPartsTypeId == cpte.Id)
         .Where((cpe, cpctve, cpte) => cpctve.CarTypeId == carTpye).OrderBy((cpe, cpctve, cpte) => cpctve.SerialNumber).Select((cpe, cpctve, cpte) => new RepCarPartsCarTypeVersion
         {
             Id = cpe.Id,
             Name = cpe.Name,
             EnglishName = cpe.EnglishName,
             Code = cpe.Code,
             CarPartsTypeName = cpte.Name,
             ReplacedCarPartsId = cpctve.ReplacedCarPartsId,
             State = cpctve.State
         }).ToListAsync();
            return list;
        }

        /// <summary>
        /// 获取车型的全部配件
        /// </summary>
        /// <param name="carTpye"></param>
        /// <returns></returns>
        public async Task<List<RepCarParts>> GetCarPartsByCarTypeId(string vehicleSeries,string carTpyeId)
        {
            var list = await sqlSugarClient.Queryable<CarPartsEntity>()
               .LeftJoin<VehicleSeriesCarPartsTypeEntity>((cp, t) => cp.CarPartsTypeId == t.Id)
               .Where((cp, t) => cp.VehicleSeriesId == vehicleSeries)
               .OrderBy((cp, t) => cp.CreateTime, OrderByType.Desc).Select<RepCarParts>().ToListAsync();

            //移出删除的数据
            var resCarParts = await GetCarPartsCarType(carTpyeId);
            List<string> deleteList= resCarParts.Where(a=>a.State==2).Select(a=>a.Id).ToList();
            List< RepCarParts> returnCarParts=new List< RepCarParts >();
            returnCarParts = list.Where(a=>!deleteList.Contains(a.Id)).ToList();

            //添加新增的数据
         List< RepCarPartsCarTypeVersion > addList= resCarParts.Where(a=>a.State==0).ToList();
            foreach (var carPart in addList)
            {
                RepCarParts rep=new RepCarParts();
                rep.Id= carPart.Id;
                rep.Name= carPart.Name;
                rep.EnglishName= carPart.EnglishName;
                rep.Code= carPart.Code;
                rep.VehicleSeriesCarPartsTypeEntityName = carPart.CarPartsTypeName;
                returnCarParts.Add(rep);
            }

            return returnCarParts;
        }
    }
}
